<?php
/**
 * @author wyl
 * @date 2015-8-5 09:50:38
 */

Yii::import('application.components.widgets.CFrontMenuProvider');
Yii::import('dao.share.class.InviteEmail');
class MyaccountController extends Controller{
	public $layout='//layouts/myaccount';
	public $navmenu;
	public $breadcrumbs=array();
	public function init(){
	    if (!Yii::app()->user->isGuest){
	        $userId=Yii::app()->user->id;
	        $order=new Orders();
	        $count=$order->countByAttributes(array(
	            "status"=>1,
	            "customer_id"=>$userId
	        ));
	        if ($count>0){
	            Yii::app()->user->setFlash("have unpaid",$count);
	        }
	    }
	    
		$provider=new CFrontMenuProvider();
        $provider->_configs = array(
    			'myprofile' => array(
    					'label' => 'MY  ACCOUNT',
    					'items' => array(
    					        'buybids'=>array(
    					            'label' => 'Buy Bids',
    					            'url' => Yii::app()->baseUrl."/myaccount/index",
    					            'position'=>array('nav')
    					        ),
    							'information' => array(
    									'label' => 'My Information',
    									'url' => Yii::app()->baseUrl."/myaccount/myinformation",
    									'position'=>array('nav')
    							),
    							'changepassword' => array(
    									'label' => 'Change Password',
    									'url' => Yii::app()->baseUrl."/myaccount/changepassword/".Yii::app()->user->id,
    									'position'=>array('nav')
    							),
    							'My ShippingAddresses' => array(
    									'label' => 'My Shipping Address',
    									'url' =>Yii::app()->baseUrl."/myaccount/shipping/",
    									'position'=>array('nav')
    							),
    							'My BillingAddresses' => array(
    									'label' => 'My Billing Address',
    									'url' =>Yii::app()->baseUrl."/myaccount/billing/",
    									'position'=>array('nav')
    							),
//     							'My Avatar' => array(
//     									'label' => 'My Avatar',
//     									'url' => Yii::app()->baseUrl."/myaccount/myavatar/".Yii::app()->user->id,
//     									'position'=>array('nav')
//     							),
    							
    							// 'Notification' => array(
    							// 		'label' => 'Notifications',
    							// 		'url' =>Yii::app()->baseUrl."/myaccount/notification/",
    							// 		'position'=>array('nav')
    							// ),
        					    'Referrals' => array(
        					        'label' => 'Referrals',
        					        'url' =>Yii::app()->baseUrl."/myaccount/invite/",
        					        'position'=>array('nav')
        					    ),
        					    'Active Auto-bid' => array(
        					        'label' => 'My Autobid',
        					        'url' =>Yii::app()->baseUrl."/myaccount/autobidlist/",
        					        'position'=>array('nav')
        					    ),
    					),
    			) ,
				'myprofile1' => array(
    					'label' => 'MY  EGUNNER',
    					'items' => array(
    							'Bidding History ' => array(
    									'label' => 'Bidding History ',
    									'url' => Yii::app()->baseUrl."/myaccount/biddinghistory",
    									'position'=>array('nav')
    							),
    							'Watchist' => array(
    									'label' => 'WatchList',
    									'url' => Yii::app()->baseUrl."/myaccount/watchlist/".Yii::app()->user->id,
    									'position'=>array('nav')
    							),
    							'Won Auctions' => array(
    									'label' => 'Won Auctions',
    									'url' => Yii::app()->baseUrl."/myaccount/wonauctions/".Yii::app()->user->id,
    									'position'=>array('nav')
    							),
    							'Bid Credit History' => array(
    									'label' => 'Bid Credit History',
    									'url' =>Yii::app()->baseUrl."/myaccount/bidcredithistory/",
    									'position'=>array('nav')
    							),
    							
    							'Order History' => array(
    									'label' => 'Order History',
    									'url' =>Yii::app()->baseUrl."/myaccount/orderhistory",
    									'position'=>array('nav')
    							),
        					    'Win Limit' => array(
        					        'label' => 'Win Limit',
        					        'url' =>Yii::app()->baseUrl."/myaccount/winlimit",
        					        'position'=>array('nav')
        					    ),
    					),
				) ,

			

    	);
        $this->navmenu=$provider;
        $this->category_category_relations=CategoryCategoryRelations::model()->findAllByAttributes(array('parent_category_id'=>'0'));
        $this->category_list=Category::model()->findAll();
        parent::init();
	}
	
	// public function actionIndex(){
	// 	$model=new Customer();
	// 	if(!empty($_GET['Customer'])){
	// 		$model->attributes=$_GET['Customer'];
	// 	}
	// 	$this->render('index',array('model'=>$model));
	// }
	public function actionIndex(){
		$this->breadcrumbs = array("My Account");
		$CustomerInfo=new CustomerBidInfo;
		$cashbid=$CustomerInfo->findByAttributes(array("customer_id"=>yii::app()->user->id,"bid_type"=>"CASH"));
		$promobid=$CustomerInfo->findByAttributes(array("customer_id"=>yii::app()->user->id,"bid_type"=>"PROMO"));
		$this->render('index',array('cashbid'=>$cashbid,'promobid'=>$promobid));
	}
	
	public function actionChange_Psd(){
		$model=new ChangePassword();
		$model->id=Yii::app()->user->id;
		if( isset($_POST['ajax']) && $_POST['ajax'] === 'changepassword_form')
		{
			echo CActiveForm::validate($model);
			Yii::app() -> end();
		}
		if(!empty($_POST['ChangePassword'])){
			$model=$model->findByPk($model->id);
			$model->attributes=$_POST['ChangePassword'];
			if($model->save()){
				echo 'Change password success!';
			}
		} 
		$this->redirect(Yii::app()->baseUrl.'/myaccount/myinfo');
	}
	
	public function actionMyinfo(){
		$this-> breadcrumbs = array(
				'My Account',
				'My Info'
		);
		$changePassword=new ChangePassword();
		$changePassword->id=Yii::app()->user->id;
		$changeEmail=new ChangeEmail();
		$model=new Customer();
		$model=$model->findByPk(Yii::app()->user->id);
		if( isset($_POST['ajax']) && $_POST['ajax'] === 'changeemail_form')
		{
			echo CActiveForm::validate($changeEmail);
			Yii::app() -> end();
		}
		if( isset($_POST['ajax']) && $_POST['ajax'] === 'changepassword_form' )
		{
			echo CActiveForm::validate($changePassword);
			Yii::app() -> end();
		}
		
		
		if(!empty($_POST['ChangeEmail'])){
			$this->layout=false;
			$changeEmail=$changeEmail->findByPk(Yii::app()->user->id);
			$changeEmail->attributes=$_POST['ChangeEmail'];
			if($changeEmail->validate() && $changeEmail->save()){
				$result=array('message'=>'Change Password Success!','new_email'=>$changeEmail->email);
				echo json_encode($result);
				Yii::app() -> end();
			}
		}
		if(!empty($_POST['ChangePassword'])){
			$this->layout=false;
			$changePassword=$changePassword->findByPk(Yii::app()->user->id);
			$changePassword->attributes=$_POST['ChangePassword'];
			if($changePassword->save()){
				$result=array('message'=>'Change Password Success!');
				echo json_encode($result);
				Yii::app() -> end();
			}
		}
		$this->render('myinfo',
					  array(
					  		'changepassword'	=>$changePassword,
					  		'changeemail'		=>$changeEmail,
					  		'model'				=>$model
					));
	}
	
	
	public function actionDashboard(){
		$tablename = Method::getBidHistoryUserTableName(Yii::app()->user->id);
		$bidhistory=new BidHistory($tablename,'search');
		$bidhistory->customer_id=Yii::app()->user->id;
		if(!empty($_GET['BidHistory'])){
			$bidhistory->attributes=$_GET['BidHistory'];
		}
		$this->render('dashboard',array('bidhistory'=>$bidhistory));
	}
	
	public function actionBidhistory(){
		$this->breadcrumbs = array("Myaccount","Bidhistory");
		$tablename = Method::getBidHistoryUserTableName(Yii::app()->user->id);
		$bidhistory=new BidHistory($tablename,'search');
		$bidhistory->customer_id=$_GET['id'];
		if(!empty($_GET['BidHistory'])){
			$bidhistory->attributes=$_GET['BidHistory'];
		}
		$this->render('bidhistory',array('bidhistory'=>$bidhistory));
	}
	public function actionMyinformation(){
		$this->breadcrumbs = array("My Account","My Information");
		$dao = new CustomerInfo();
		$dao=$dao->findByAttributes([
			"customer_id"=>Yii::app()->user->id
		]);
		if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
		{
			echo CActiveForm::validate($dao);
			Yii::app()->end();
		}
		if(!empty($_POST)){
			$dao->attributes=$_POST['CustomerInfo'];
			$dao->birthday=strtotime($dao->birthday);
			$result=$dao->save(false);
			if(!empty($result)){
			    $data=array();
			    $data=$_POST['CustomerInfo'];
                $data['username']=Yii::app()->user->name;
			    $url='painfo.php';
			    $return_arr=$this->sendCurl($data,$url);
			}
		}
		$states=State::model()->findAll('country_id=10');
		$this->render('myinformation',array('model'=>$dao,'states'=> $states));
		
	}
	public function actionChangepassword(){
		$this->breadcrumbs = array("My Account","Change Password");
	    $model=new  Customer();
	    if(isset($_POST['ajax']) && $_POST['ajax']==='user-pass'){  
			    echo CActiveForm::validate($model);  
			    Yii::app()-> end();  
			}  
		
		$this->render('changepassword',array('model'=>$model));
	}
	/**
	 * ajax 修改密码接口
	 * 验空，验重复，验原密码
	 * 同步Egunner 密码修改
	 */
	public function actionAjaxchangepass(){
	    
		if(!empty($_POST['Customer'])){
		    $model=Customer::model()->findByPk(Yii::app()->user->id);
		    $salt=$model->salt;
		    
		    if($_POST['Customer'][0]==""){
		    	echo   "The old password can not be empty ";
		    }
		    else if($_POST['Customer'][1]==""){
		    	echo "The new password can not be empty";
		    }
		    else if($_POST['Customer'][2]==""){
		    	echo "The confirm password can not be empty";
		    }
		    else  if(strlen($_POST['Customer'][1])<=5){
		    	echo "The  new  Password is too short (minimum is 6 characters)";
		    }
		    else{
		   
		    	if($model->password!=$this->ppb_password_hash($_POST['Customer'][0], $salt)){
		    		echo "Old password is not correct";
			   	}
			   	else {
			   		if($model->password==$this->ppb_password_hash($_POST['Customer'][1], $salt)){
			   			echo "Old and new passwords can not be the same";
			   		}else{
			   			if($_POST['Customer'][1]==$_POST['Customer'][2]){
			   			    $salt=$this->create_salt();			
			   			    $result=$model->updateAll(array(
			   			        'password'=>$this->ppb_password_hash($_POST['Customer'][1], $salt),
			   			        'salt'=>$salt
			   			        
			   			    ),
			   			        'id='.Yii::app()->user->id
			   			    );
			   			    if(!empty($result)){
			   			        $data=array();
			   			        $data['password']=$this->ppb_password_hash($_POST['Customer'][1], $salt);
			   			        $data['salt']=$salt;
			   			        $data['username']=$model->user_name;
			   			        $url='papassword.php';
			   			        $return_data=$this->sendCurl($data,$url);
			   			        echo   "update  successfully";
			   			    }
					   		
						}
						else{
							echo   "Two times the password does not match";
						}
			   		}
			   	}
		    }
		}
	}
	/**
	 * 数据同步接口
	 * @param array $data
	 * @param str $url 接口文件(.PHP 后缀)
	 */
	public function sendCurl($data,$url){
	    $url = Yii::app()->params['egunner'].$url;
	    $ch = curl_init($url);
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_HEADER, 0 );
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	    $output = curl_exec($ch);
	    if (curl_errno($ch)) {
	        echo 'Errno'.curl_error($ch);
	    }
	    curl_close($ch);
	    return $output;
	}
	/**
	 * 密码加密机制
	 * @param unknown $password
	 * @param unknown $salt
	 * @return string
	 */
	function ppb_password_hash ($password, $salt)
	{
	    return md5(md5($password) . $salt);
	}
	/**
	 * 生成随机码
	 * @return string
	 */
	function create_salt()
	{
	    $rand = md5(rand(2, 99999999));
	    $output = substr($rand, 0, 3);
	
	    return $output;
	}
	//返回model
	public function actionNotification(){
		$this->breadcrumbs = array("My Account","Notifications");
		$not_history=new CustomerMessage();
// 	    $not_history=CustomerMessage::model()->findAll('customer_id=:customer_id  and enable=1 ',array(':customer_id'=>Yii::app()->user->id));
		$this->render('notification',array('not_history'=>$not_history));
	}
	//返回model和数组$bidnum，这个关联5个表所以比较麻烦，你看看我当时更新的view吧。
	public function actionBiddinghistory(){
		$this->breadcrumbs = array("My Account","Bidding History");
		
//		$tablename = Method::getBidHistoryUserTableName(Yii::app()->user->id);
		$bidhistory=new AuctionBidLog();

	    $this->render('Biddinghistory',array('bidhistory'=>$bidhistory));
	}
	//返回model		关联AuctionInfo    想调用AuctionInfo 信息。 可以这么写$watchlist[0]['AuctionInfo']
	public function actionWatchlist(){
		$this->breadcrumbs = array("My Account","WatchList");
		$watchlist=new Favorites();
		$this->render('watchlist',array('watchlist'=>$watchlist));
	}
	public function actionWonauctions(){
		$this->breadcrumbs = array("My Account","Won Auctions");
		$wauction=new Orders();
		// $wauction=AuctionInfo::model()->with('Orders')->findAll( 'customer_id=:customer_id and  t.status=2 and type=1 ',array(':customer_id'=>Yii::app()->user->id));
		$this->render('wonauctions',array('wauction' => $wauction,));
	}	
	//返回model  记得给我order_id，还要判断$orderhistory是否存在啊！
// 	public function actionOrderhistory(){
// 		 if(!empty($_GET['order'])){
// 		 	$order_id=$_GET['order'];
// 	    	$orderhistory=Orders::model()->findAll( 'customer_id=:customer_id  and  id=:order_id',array(':customer_id'=>Yii::app()->user->id,':order_id'=>$order_id));
// 	    	$this->render('orderhistory',array('orderhistory'=>$orderhistory));
// 		 }else{
// 		 	$orderhistory=Orders::model()->findAll( 'customer_id=:customer_id',array(':customer_id'=>Yii::app()->user->id));
// 			$this->render('orderhistory',array('orderhistory'=>$orderhistory));
// 		 }   
// 	}
	public function actionOrderhistory(){
		$this->breadcrumbs = array("My Account","Order History");
		$ohistory = new UserOrder('serach');
		$ohistory->unsetAttributes();
		$ohistory->customer_id = Yii::app()->user->id;
		$this->render('ohistory',array(
				'ohistory' => $ohistory,
		));
	}
	//返回model,
	public  function actionBidcredithistory(){
		$this->breadcrumbs = array("My Account","Bid Credit History");
		$model=new EarnedBidLog();
// 		$phistory=EarnedBidLog::model()->findAll( 'customer_id=:customer_id  and bid_type = 1',array(':customer_id'=>Yii::app()->user->id));
		$this->render('bidcredithistory',array(
			'model'=>$model->search_my()
		));
	}
	//返回model,是auctions和Orders的关联查询
	public function actionWauctions(){
		$wauction=AuctionInfo::model()->with('Orders')->findAll( 'customer_id=:customer_id and  t.status=2 and type=1 ',array(':customer_id'=>Yii::app()->user->id));
		$this->render('wauction',array(
				'wauction' => $wauction,
		));
	}
	public  function actionMyavatar(){
		$this->breadcrumbs = array("My Account","My Avatar");
		$Customer=new CustomerInfo();
		$avatar=$Customer->findByAttributes(array('customer_id'=>Yii::app()->user->id));
		$this->render('myavatar',array("imgpath"=>$avatar->avatar));

	}
	//ajax头像修改
	public function actionAjaxavatar(){

		if(!empty($_POST["img_num"])){
			$Customer=new CustomerInfo();
			$avatar=$Customer->findByAttributes(array('customer_id'=>Yii::app()->user->id));
			$avatar->avatar=Yii::app()->resource->path('')."/images/avatar/headimg".$_POST["img_num"].".jpg";
            
			$return=$avatar->update();
			if($return){
				echo "success";
			}
			else{
				echo "fail";
			}
			

		}

	}
	public function actionBilling(){
		$this->breadcrumbs = array("My Account","My Billing Address");
		$bill=CustomerOrderBillingInfo::model()->find('customer_id=:customer_id',array(':customer_id'=>Yii::app()->user->id));
		if(count($bill)>0){
			$billing =CustomerOrderBillingInfo::model()->findByPk($bill['id']);;
		}else{
			$billing = new CustomerOrderBillingInfo();
		}		

		if(Yii::app()->request->isPostRequest){
			$data = Yii::app()->request->getPost('CustomerOrderBillingInfo');
			$billing->attributes = $data;
			$billing->created = time();
			$billing->customer_id = Yii::app()->user->id;
			$res = $billing->save();
			
			if(Yii::app()->request->isAjaxRequest){
				Yii::app()->end();
			}
		}
		$this->render('billing', array(
			'model'=>$billing,
			'country' => Country::model()->findAll('id=10'),
			'state' => State::model()->findAll('country_id=10 order by name'),
		));
	}
	
	public function actionInvite(){
	    $model=new InviteEmail('generate');
	    if (Yii::app()->user->isGuest){
	       $this->redirect(Yii::app()->baseUrl.'/login');
	    }
	    $model->customerId=Yii::app()->user->id;
	    $emails=!empty($_POST['emails'])?$_POST['emails']:array();
	    if (!empty($emails)){
	        $errors=array();
	         foreach ($emails as $email){
	             $sendReferEmail=new InviteEmail("generate");
	             $sendReferEmail->email=$email;
	             $sendReferEmail->customerId=Yii::app()->user->id;
	             if ($sendReferEmail->validate()){
	                 $sendReferEmail->generate();
	             }
	             $errors=$sendReferEmail->getErrors();
	         }
	         echo json_encode(array('msg'=>'successful','error'=>$errors));
	         Yii::app()->end();
	    }
	    $totalNum=InviteSuccess::model()->countByAttributes(array('customer_id'=>$model->customerId));
	    $tablename = Method::getBidHistoryUserTableName(Yii::app()->user->id);
		$bidhistory=new BidHistory($tablename);
	    $totalPromo=$bidhistory->countByAttributes(array(
	        'customer_id'=>$model->customerId,
	        'bid_source_type'=>'INVITE',
	        'bid_type'=>'PROMO'
	    ));
	    $this->render('invite',array(
	        'model'=>$model,
	        'totalNum'=>$totalNum,
	        'totalPromobid'=>$totalPromo
	    ));
	}
	
	
	public function actionShipping(){
		$this->breadcrumbs = array("My Account","My Shipping Address");
		/* 原代码
		 * $ship=CustomerOrderShippingInfo::model()->find('customer_id=:customer_id',array(':customer_id'=>Yii::app()->user->id));
		
	   if(count($ship)>0){
			$shipping =CustomerOrderShippingInfo::model()->findByPk($ship['id']);;
		}else{
			$shipping = new CustomerOrderShippingInfo();
		}
		if(Yii::app()->request->isPostRequest){
			$data = Yii::app()->request->getPost('CustomerOrderShippingInfo');
			$shipping->attributes = $data;
			$shipping->customer_id = Yii::app()->user->id;
			$res = $shipping->save();
			if(Yii::app()->request->isAjaxRequest){
				Yii::app()->end();
			}
		} */
		
		/**
		 * edit by wyl
		 */
		$shipping=new CustomerOrderShippingInfo();
		$shipping=$shipping->findByAttributes([
		    "customer_id"=>Yii::app()->user->id
		]);
		if (empty($shipping)){
		    $shipping=new CustomerOrderShippingInfo();
		}
		$shipping->customer_id=Yii::app()->user->id;
		if (!empty($_POST)){
		    $shipping->attributes=$_POST["CustomerOrderShippingInfo"];
		    $shipping->save();
		}
		$this->render('shipping', array(
				'model'=>$shipping,
				'country' => Country::model()->findAll('id=10'),
				'state' => State::model()->findAll('country_id=10 order by name'),
		));
	}
	
	
	public function actions(){
		return array(
				'captcha'=>array(
						'class'=>'CCaptchaAction',
						'backColor'=>0xFFFFFF,
						'maxLength'=>'4',       
						'minLength'=>'4',       
						'height'=>'35'
			),
		);
	}
	
	public function actionWinlimit(){
	    $auctionLimit=new AuctionLimit();
	    $this->render("winlimit",array(
	        'winlimit'=>$auctionLimit
	    ));
	}
	
	/**
	 * autobid  list列表
	 */
	public function actionAutobidlist(){
	    $autobid=new Autobid();
	    $this->render("autobidlist",array(
	        'autobid'=>$autobid
	    ));
	}
	
	/**
	 * 删除autobid
	 */
	public function actionDelete(){
	    $autobid=new Autobid();
	    $autobid=$autobid->findByPk($_GET["autobidId"]);
	    if (!empty($autobid)){
            $tmpautobid=new AutobidLog();
            $tmpautobid->attributes=$autobid->attributes;
			$tmpautobid->sort = 0;
            $tmpautobid->save();
	    }
	    $result=AutoBid::model()->deleteAllByAttributes(array('id'=>$_GET['autobidId']));
	    echo json_encode(array('result'=>$result));
	}
}